<template>
	<view class="">
		<view class="sticky top-0" style="z-index: 100;">
			<view class="all-header chart-head">
				<view :style="{height:statusBarHeight}"></view>
				<view class="h-44p flex justify-center items-center" style="color: #fff;">
					<view>
						<uni-data-select class="date-pick" :clear="false" v-model="datePickType"
							:localdata="dateTypeRange" @change="changeDateType"></uni-data-select>
					</view>

				</view>
				<view class="time">
					<view class="time-left">
						<view @click="changeDatePick">{{ parseDateStr }}</view>
						<KDatePicker v-model="show" :defaultValue="curDateNum" @change="changeDate"
							:type="datePickType"></KDatePicker>
					</view>

				</view>
				
			</view>
		</view>
		
		<view class="p-10">
			<div class="total">
				<view class="total-item">
					<view class="title">{{ '共支出' }}</view>
					<view class="expense">{{ formatMoney(payTotal) }}</view>
				</view>
				<view class="total-item">
					<view class="title">{{ '共入账' }}</view>
					<view class="expense">{{ formatMoney(incomeTotal) }}</view>
				</view>
			</div>
			<view v-if="pieChartData.length>0" class="flex flex-column px-20 pb-24 bg-white pb-20"
				style="border-bottom: 2px dashed #eee;border-radius: 5px;">
				<view class="chang-item">
					<view class="chang-item-list">
						<view class="chang-item-text" @click="changeType(0)"
							:style="{'color':type === 0 ?'#000':'','backgroundColor': type === 0 ?'#fff':''}">支出</view>
						<view class="chang-item-text" @click="changeType(1)"
							:style="{'color':type === 1 ?'#000':'','backgroundColor': type === 1 ?'#fff':''}">收入</view>
					</view>
				</view>
				<view class="pt-10  bg-white" style="z-index: 3; top: 199px;">
					<text style="font-weight: bold;margin-left: 5px"
						class="mb-10">{{datePickType==='month' ?'月度':datePickType==='year'?'年度':'当日'}}{{ type ? '收入' : '支出' }}对比</text>
				</view>
			
				<view class="charts-box bg-white">
					<l-echart style="width: 90vw;height: 100%" ref="dayHistogramOptionChart">
					</l-echart>
				</view>
				
			</view>
			<!-- 支出/收入排行榜 -->
			<view v-if="pieChartData.length>0" class="flex flex-column px-20 pb-24 bg-white"
				style="border-bottom: 2px dashed #eee;">
				<view class="pt-20  bg-white" style="z-index: 3; top: 199px;">
					<text style="font-weight: bold;margin-left: 5px" class="mb-10">收支构成</text>
				</view>
				<view class="charts-box bg-white">
					<l-echart style="width: 90%;height: 100%" ref="pieChart">
					</l-echart>
				</view>
			
				<view class="pt-20 pb-10 bg-white" style="z-index: 3; top: 199px;">
					<text style="font-weight: bold;margin-left: 5px" class="mb-10">{{ type ? '收入' : '支出' }}排行</text>
				</view>
				<view>
					<view>
						<view v-for="(item,index) in showPieChartData" class="flex items-center"
							@click="go(item.type_id,item.title,1)">
							<text class="iconfont bg p-16r mr-20r" :class="item.icon"
								:style="{backgroundColor:type === 0? systemTheme.outColor:systemTheme.inColor}"
								style="font-size: 30px; border-radius:50%;color: white;"></text>
							<view class="flex-auto flex flex-column py-20">
								<view class="flex">
									<text>{{ item.title }}&nbsp;&nbsp;<text class="text-14 text-666">{{ item.rate }}</text>
									</text>
			
								</view>
								<view style="background-color: #eee;width: 90%" class="rounded-3">
									<view class="h-6p rounded-3"
										:style="{width:item.rate,'background-color':type === 0? systemTheme.outColor:systemTheme.inColor}">
									</view>
								</view>
							</view>
			
							<view class="flex items-center">
								<view class="flex flex-column items-end ml-10">
									<text class="text-333 mb-6">￥{{ formatMoney(item.num) }}</text>
									<text class="text-666 text-12">{{ item.count }}笔</text>
								</view>
								<text class="iconfont icon-right ml-6 text-333"></text>
							</view>
						</view>
						<view v-if="pieChartData.length>5  && !showAllPieChartDataFlag"
							style=" height: 30px;width: 100%;color: #999;display: flex;font-size: 16px;align-items: center;justify-content: center">
							<view @click="changeShowPieData(true)" class="gotoDetail">
								<text>展开更多</text>
								<text class="iconfont icon-arrow-down"></text>
							</view>
						</view>
						<view v-if="pieChartData.length>5  && showAllPieChartDataFlag"
							style=" height: 30px;width: 100%;color: #999;display: flex;font-size: 16px;align-items: center;justify-content: center">
							<view @click="changeShowPieData(false)" class="gotoDetail">
								<text>收起</text>
								<text class="iconfont icon-arrow-up"></text>
							</view>
						</view>
					</view>
				</view>
			
			</view>
			
			<view v-else class="empty flex-auto flex flex-column justify-center items-center"
				style="height: 200px;align-items: center">
				<text class="iconfont icon-wushuju"></text>
				<text>暂无数据</text>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		formatMoney
	} from '@/common/format.js'
	import KDatePicker from "../../components/k-date-picker/KDatePicker.vue";

	import dayjs from 'dayjs'
	import * as echarts from 'echarts'
	import {
		getRankByDate,
		getLineByRange,
		getRank
	} from "../../api/api";
	import {
		useSystem
	} from "@/store/theme";

	export default {
		components: {
			KDatePicker
		},
		data() {
			return {
				dateTypeRange: [{
						value: 'month',
						text: "月度"
					},
					{
						value: 'year',
						text: "年度"
					},
					{
						value: 'date',
						text: "日期"
					},
				],
				datePickType: 'month',
				show: false,
				dayHistogramOption: {},
				monthHistogramOption: {},
				type: 0,
				current: 0,
				curYear: null,
				curMon: null,
				curDay: null,
				dateValue: null,
				currentDate: null,


				pieChartData: [],
				showPieChartData: [],
				showAllPieChartDataFlag: false,

				lineData: [],
				dateStrList: [],
				rankByDateList: [],

				chartData: [],
				curDateNum: 0,
				payTotal: 0,
				incomeTotal: 0

			}
		},
		setup() {
			const systemTheme = useSystem()
			return {
				systemTheme
			}
		},
		computed: {
			parseDateStr() {
				if (this.datePickType === 'month') {
					return this.curYear + '年' + this.curMon + '月'
				}
				if (this.datePickType === 'year') {
					return this.curYear + '年'
				}
				if (this.datePickType === 'date') {
					return this.curYear + '年' + this.curMon + '月' + this.curDay + '日'
				}
			},

			
			statusBarHeight() {
				return (uni.getSystemInfoSync()).statusBarHeight + 'px'
			}
		},
		async onPullDownRefresh() {
			const date = new Date()
			await this.parseDate(date)
			await this.getData()
			uni.stopPullDownRefresh();
		},
		
		async onShow() {
			const date = new Date()
			await this.parseDate(date)
			await this.getData()
			this.initData()
		},
		methods: {
			async initData() {
				const pieChartData = await getRank(0, this.curYear, this.curMon, this.curDay)
				const pieChartData2 = await getRank(1, this.curYear, this.curMon, this.curDay)
				this.payTotal = pieChartData.reduce((accumulator, currentItem) => accumulator + currentItem.num, 0);
				this.incomeTotal = pieChartData2.reduce((accumulator, currentItem) => accumulator + currentItem.num, 0);
			
			},
			getTotal() {
				let sum = 0
				if (this.pieChartData != null && this.pieChartData.length > 0) {
					sum = this.pieChartData.reduce((accumulator, currentItem) => accumulator + currentItem.num, 0);
					this.pieChartData.map(item => {
						item.rate = (item.num / sum * 100).toFixed(2) + '%'
					})
				}
				return sum
			},
			changeShowPieData(flag) {

				if (flag === undefined || flag === null) {
					this.showAllPieChartDataFlag = !this.showAllPieChartDataFlag
				} else {
					this.showAllPieChartDataFlag = flag
				}

				if (this.showAllPieChartDataFlag) {
					this.showPieChartData = this.pieChartData
				} else {
					this.showPieChartData = this.pieChartData.slice(0, 5)
				}



			},
			async changeType(e) {
				this.type = e;
				await this.parseDate(new Date())
				this.getData()
			},
			async setHistogramChart() {
				let _data = []

				if (this.dateStrList !== undefined && this.dateStrList.length > 0) {
					let tmpMap = {}
					this.lineData.forEach(item => {
						if (this.datePickType === "year") {
							tmpMap[item.year] = item;
						} else if (this.datePickType === "month") {
							tmpMap[item.month] = item;
						} else if (this.datePickType === "date") {
							tmpMap[item.date] = item;
						}
					})

					let initYear = this.dateStrList[0].date.getFullYear()
					let flag = true
					_data = this.dateStrList.map((item, index) => {
						let tmpItem = {
							num: 0
						}
						let mapElement = tmpMap[item.dateString]

						if (mapElement !== undefined) {
							tmpItem.num = mapElement.num;
						}

						if (this.datePickType === 'year') {
							tmpItem.xValue = item.dateString + '年'
						} else if (this.datePickType === 'month') {
							tmpItem.xValue = dayjs(item.date).format('MM月')
							if (flag) {
								const year = item.date.getFullYear()
								if (year !== initYear) {
									tmpItem.xValue += '\n' + year
									flag = false
								}
							}

						} else if (this.datePickType === 'date') {
							tmpItem.xValue = dayjs(item.date).format('MM.DD')
							if (flag) {
								const year = item.date.getFullYear()
								if (year !== initYear) {
									tmpItem.xValue += '\n' + year
									flag = false
								}
							}
						}
						return tmpItem;
					})

				}


				let color = this.type === 0 ? this.systemTheme.shallowOutColor : this.systemTheme.shallowInColor

				let xAxisData = _data.map(item => {
					return item.xValue
				})


				let yAxisData = _data.map(item => {
					let tmpData = {
						value: item.num,
						itemStyle: {
							color: color,
							borderRadius: [20, 20, 0, 0],
						},
						patType: this.type
					}
					if (this.datePickType === 'year') {
						tmpData.dateStr = item.year
					}
					if (this.datePickType === 'month') {
						tmpData.dateStr = item.month
					}
					if (this.datePickType === 'date') {
						tmpData.dateStr = item.date
					}
					return tmpData;
				})

				if (yAxisData[yAxisData.length - 1] != null) {
					yAxisData[yAxisData.length - 1].itemStyle.color = this.type === 0 ? this.systemTheme.outColor :
						this.systemTheme.inColor
				}


				this.dayHistogramOption = {
					tooltip: {
						trigger: 'axis',
						// shadowBlur: 0,
						textStyle: {
							color: '#FFF', // 文字的颜色
							fontStyle: 'normal', // 文字字体的风格（'normal'，无样式；'italic'，斜体；'oblique'，倾斜字体）
							fontWeight: 'normal', // 文字字体的粗细（'normal'，无样式；'bold'，加粗；'bolder'，加粗的基础上再加粗；'lighter'，变细；数字定义粗细也可以，取值范围100至700）
							// fontSize: '20', // 文字字体大小
							// lineHeight: '50', // 行高
						},
						axisPointer: {
							type: 'line', // 指示器类型（'line' 直线指示器；'shadow' 阴影指示器；'none' 无指示器；'cross' 十字准星指示器。）
							snap: false, // 坐标轴指示器是否自动吸附到点上。默认自动判断。
							animation: true, // 是否开启动画
							animationDuration: 1000, // 初始动画时长
							animationDurationUpdate: 200, // 数据更新动画的时长
						},
						backgroundColor: 'rgba(50,50,50,0.7)',
						renderMode: 'richText',
					},
					calculable: true,
					xAxis: [{
						type: 'category',
						data: xAxisData
					}],
					yAxis: [{
						type: 'value',
						axisLabel: {
							formatter: function(value, index) {
								const abbreviations = {
									b: 1000000000,
									m: 1000000,
									w: 10000,
									k: 1000
								};

								for (let key in abbreviations) {
									if (value >= abbreviations[key]) {
										return (value / abbreviations[key]) + key;
									}
								}

								return value;
							}
						}
					}],
					series: [{
						name: '金额',
						type: 'bar',
						data: yAxisData,
						barWidth: 10
					}]
				}
				// chart 图表实例不能存在data里
				const chart = await this.$refs.dayHistogramOptionChart.init(echarts);
				chart.setOption(this.dayHistogramOption)
			},
			changeDateType(e) {
				this.datePickType = e
				const date = new Date()
				this.parseDate(date)
				this.getData()
				this.initData()
			},
			changeDatePick() {
				if (this.show) {
					this.show = false
				}
				this.show = true
			},
			async changeDate(e) {
				if (typeof e === 'number' && !isNaN(e)) {
					const date = new Date(e);
					await this.parseDate(date)
					await this.getData()
				}
			},
			async parseDate(e) {
				let date = new Date();
				if (e) {
					date = e;
				}
				this.currentDate = date
				this.curMon = null;
				this.curDay = null;
				if (this.datePickType === 'month') {
					this.curMon = (date.getMonth() + 1)
				}
				if (this.datePickType === 'date') {
					this.curMon = (date.getMonth() + 1)
					this.curDay = date.getDate()
				}
				this.curYear = date.getFullYear().toString()

			},
			async setPieChart() {
				let _data = this.pieChartData.map(item => {
					return {
						category: item.title,
						amount: item.num
					}
				});

				if (_data === null || _data.length === 0) {
					return;
				}

				if (_data.length > 10) {
					let tmpArr = _data.slice(9, _data.length);
					let amount = 0;
					let category = "更多分类";

					tmpArr.map((item) => {
						amount += item.amount;
					})

					_data[9].amount = amount;
					_data[9].category = category;
					_data = _data.slice(0, 10);
				}


				this.pieOption = {
					color: this.type === 0 ? this.systemTheme.outColorChatList : this.systemTheme.inColorChatList,
					series: [{
						name: '收支统计',
						type: 'pie',
						radius: ['30%', '55%'],
						avoidLabelOverlap: false,
						itemStyle: {
							borderRadius: 10,
							borderColor: '#fff',
							borderWidth: 2
						},
						emphasis: {
							label: {
								show: true,
								fontWeight: 'bold'
							}
						},
						label: {
							fontWeight: 'bold',
							color: '#999',
							formatter: '{name|{b}}',
							minMargin: 0,
							edgeDistance: 10,
							lineHeight: 0,
							rich: {
								time: {
									fontSize: 10,
									color: '#999'
								}
							}
						},
						data: _data.map(item => {
							return {
								value: item.amount,
								name: item.category
							}
						})
					}]
				}

				// chart 图表实例不能存在data里
				const chart = await this.$refs.pieChart.init(echarts);
				chart.setOption(this.pieOption)
			},
			go(id, title, chartType) {
				uni.navigateTo({
					url: '/pages/chart/rankDetail?type_id=' + id + '&type_title=' + title + '&date_type=' + this
						.datePickType + '&year=' + this.curYear + '&month=' + this.curMon + '&day=' + this.curDay +
						'&type=' + this.type + '&chart_type=' + chartType
				})
			},
			formatMoney(num) {
				return formatMoney(num)
			},
			async getData() {
				// 获取根据类目统计数据
				this.pieChartData = await getRank(this.type, this.curYear, this.curMon, this.curDay)
				this.getTotal()
				this.changeShowPieData(false)
				// 获取排行数据
				this.rankByDateList = await getRankByDate(this.type, this.curYear, this.curMon, this.curDay, 0, 10)
				if (this.rankByDateList) {
					this.rankByDateList.forEach(item => {
						item.create_time_str = dayjs(item.create_time).format('M月D日 HH:mm:ss')
					})
				}

				// 获取根据时间统计数据
				this.dateStrList = this.getDateRange(this.datePickType, this.currentDate)
				if (this.dateStrList) {
					let strArr = this.dateStrList.map((item) => {
						return item.dateString;
					})
					this.lineData = await getLineByRange(this.type, this.datePickType, strArr)
				}

				// 渲染统计图 无数据则跳过渲染
				if (this.pieChartData !== null && this.pieChartData.length !== 0) {
					await this.setPieChart()
					await this.setHistogramChart()
				}
				// setTimeout(function() {
				// 	uni.hideLoading()
				// }, 800);
			},
			getDateRange(type, currentDate) {
				let tmpDate = currentDate
				let result = [];

				if (type === 'month') {
					for (let i = 0; i < 6; i++) {
						let month = tmpDate.getMonth() + 1;
						let year = tmpDate.getFullYear();
						let dateString = `${year}-${month.toString().padStart(2, '0')}`;
						result.push({
							dateString,
							type: 'month',
							date: new Date(tmpDate.getTime())
						});

						tmpDate.setMonth(tmpDate.getMonth() - 1);
					}
				} else if (type === 'date') {
					for (let i = 0; i < 30; i++) {
						let day = tmpDate.getDate();
						let month = tmpDate.getMonth() + 1;
						let year = tmpDate.getFullYear();
						let dateString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
						result.push({
							dateString,
							type: 'date',
							date: new Date(tmpDate.getTime())
						});

						tmpDate.setDate(tmpDate.getDate() - 1);
					}
				} else if (type === 'year') {
					for (let i = 0; i < 5; i++) {
						let year = tmpDate.getFullYear();
						let dateString = `${year}`;
						result.push({
							dateString,
							type: 'year',
							date: new Date(tmpDate.getTime())
						});

						tmpDate.setFullYear(tmpDate.getFullYear() - 1);
					}

				}

				return result.reverse();
			}

		}
	}
</script>

<style scoped lang="scss">
	.chart-head {
		background-color: #fff;
		margin-bottom: 15px;
		box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2);

	}

	.active {
		color: white;
		background-color: #000;
	}

	.tabTitle {
		//background-color: #42b479;

		text {
			flex-basis: 50%;
			text-align: center;
			padding: 12rpx 0;
			border: 1px solid #000;
		}
	}


	.charts-box {
		width: 100%;
		height: 35%;
		display: flex;
		justify-content: center;
		/* 水平居中 */
	}

	.empty {
		color: #ccc;

		.iconfont {
			font-size: 60px;
			margin-bottom: 10px;
		}
	}

	.time {
		width: 100%;
		display: flex;
		justify-content: center;

		.time-left {
			display: flex;
			// width: 70%;
			overflow: hidden;
			border-radius: 4px;
			font-size: 18px;
			margin-left: 20rpx;
			margin-bottom: 38rpx !important;
			flex-direction: row;
			align-items: center;
		}

		.time-right {
			width: 30%;

			span {
				width: 40px;
				height: 24px;
				color: white;
				text-align: center;
				line-height: 24px;
				margin-right: 20px;
				border-radius: 4px;
			}
		}
	}

	.total {
		//background-color: #fff;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		background-color: #fff;
		border-radius: 8px;
		padding: 10px;
		margin-bottom: 15px;
		.total-item {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.title {
			margin-left: 20rpx;
			font-size: 16px;
			margin-bottom: 5px;
			color: #ccc;
		}

		.expense {
			margin-left: 20rpx;
			font-size: 18px;
			font-weight: bold;
		}
	}

	.date-pick {
		:deep(.uni-select) {
			border: 0;
			font-size: 18px;
			font-weight: bold;
			color: black;
		}

		:deep(.uni-select__input-text) {
			text-align: center;
		}

		:deep(.uni-icons uniui-bottom) {
			border: 0;
			font-size: 18px;
			color: black;
		}
	}

	.gotoDetail:active {
		font-weight: bold;
	}

	.chang-item {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 10px;

		.chang-item-list {
			display: flex;
			align-items: center;
			background-color: #f0f0f0;
			padding: 4px 6px;
			border-radius: 20px;

			.chang-item-text {
				font-size: 14px;
				padding: 4px 6px;
				border-radius: 20px;
				color: #9a9a9a;
			}
		}
	}
</style>